<template>
  <div>
    <van-nav-bar title="城市列表" left-arrow @click-left="$router.back()" />
    <van-index-bar :index-list="ListKey">
      <span>
        <van-index-anchor index="当前城市" />
        <van-cell :title="city" />
      </span>
      <span>
        <van-index-anchor index="热门城市" />
        <van-cell
          @click="cityFn(hostitem.label)"
          v-for="(hostitem, hostindex) in hostcity"
          :key="hostindex"
          :title="hostitem.label"
        />
      </span>
      <span v-for="(value, key, index) in cityobj" :key="index">
        <van-index-anchor :index="key" />
        <van-cell
          @click="cityFn(item.label)"
          v-for="(item, idex) in value"
          :key="idex"
          :title="item.label"
        />
      </span>
    </van-index-bar>
  </div>
</template>

<script>
import { city, host, areaIhfo } from '@/api/article'
import { getCityname, setCityname, setCitycode } from '@/utils/storage'
export default {
  async created() {
    const { body } = await city()
    const res = await host()
    // console.log(res)
    this.list = body
    this.paixu()
    this.hostcity = res.body
    this.city = getCityname()
  },
  data() {
    return {
      list: [],
      city: '',
      hostcity: [],
      cityobj: {},
      ListKey: [],
      obj: {
        name: 1,
        aeg: [1, 2]
      }
    }
  },
  methods: {
    paixu() {
      for (let i = 65; i < 91; i++) {
        this.ListKey.push(String.fromCharCode(i))
      }
      let city = this.list.map((item) => {
        item['key'] = item.pinyin.slice(0, 1).toLocaleUpperCase()
        return item
      })
      let num = 0
      for (let i = 0; i < this.ListKey.length; i++) {
        // this.cityobj[this.ListKey[i]] = []
        this.$set(this.cityobj, this.ListKey[i], [])
        for (let j = 0; j < city.length; j++) {
          if (city[j].key === this.ListKey[i]) {
            // this.cityobj[this.ListKey[i]].push(city[j])
            this.$set(this.cityobj[this.ListKey[i]], num, city[j])
            num++
          }
        }
        if (!this.cityobj[this.ListKey[i]].length) {
          delete this.cityobj[this.ListKey[i]]
          delete this.ListKey[i]
        }
        num = 0
        // console.log(this.ListKey[i]);
      }
      this.ListKey.splice(0, 0, '#', '热')
      // console.log(this.cityobj)
      // console.log(this.ListKey);
    },
    async cityFn(val) {
      this.city = val
      const {
        body: { label, value }
      } = await areaIhfo(val)
      setCityname(label)
      setCitycode(value)
      this.$router.back()
    }
  }
}
</script>

<style lang="less" scoped>
.title {
  font-size: 14px;
  color: #acacac;
}
</style>
